<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="用户角色" prop="isLawyerName">
                    <el-select class="flex-1" v-model="formData.isLawyerName" placeholder="请选择用户角色" @change="roleChange">
                        <el-option v-for="(item, index) in dictData.user_role" :key="index" :label="item.name" :value="item.value"/>
                    </el-select>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { getUserDetail, editRole } from '@/api/consumer'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const roleChange = (value) => {
    formData.isLawyer = value;
}

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'handleBalance' ? '编辑余额' : '修改角色'
})

const formData = reactive({
    id: '',
    isLawyer: '',
    isLawyerName: ''
})

const formRules = reactive({
    isLawyer: [
        {
            required: true,
            message: '请选择角色',
            trigger: ['blur']
        }
    ],
})

const handleSubmit = async () => {
    await formRef.value?.validate()

    await editRole(formData)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (row: any) => {

    const data = await getUserDetail({
        id: row.id
    })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData
})
</script>
